#!/bin/bash

# Function to convert file line endings from CRLF to LF
convert_line_endings() {
  local file="$1"
  # Use dos2unix to convert line endings if it's installed
  if command -v dos2unix >/dev/null 2>&1; then
    dos2unix "$file"
  else
    # Use sed to replace CRLF with LF
    sed -i '' 's/\r$//' "$file"
  fi
}

# Function to convert file encoding from GB2312 to UTF-8
convert_encoding() {
  local file="$1"
  # Check file encoding
  local encoding
  encoding=$(file -bi "$file" | awk -F "=" '{print $2}')
  
  if [ "$encoding" = "gb2312" ] || [ "$encoding" = "gbk" ] || [ "$encoding" = "iso-8859-1" ]; then
    # Convert encoding from GB2312/GBK to UTF-8
    enconv -c -L chinese -d -V -x utf-8 $file
  fi
}

# Recursive function to process each file in the directory
process_directory() {
  local dir="$1"
  
  for file in "$dir"/*; do
    if [ -d "$file" ]; then
      # If it's a directory, process it recursively
      process_directory "$file"
    elif [ -f "$file" ]; then
      # If it's a file, convert line endings and encoding
      convert_encoding "$file"
      convert_line_endings "$file"
    fi
  done
}

# Start processing from the current directory
process_directory "$(pwd)"